package app.controller;

import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

import org.apache.catalina.servlet4preview.http.HttpServletRequest;
import org.apache.commons.io.FileUtils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import app.config.Config;

import app.domain.Assess;
import app.domain.DiscountedChart;

import app.domain.FileInfo;
import app.domain.Result;
import app.domain.Worker;
import app.domain.WorkerChart;
import app.service.CommentService;
import app.service.FileService;
import app.service.FixOrderService;
import app.service.WorkManageService;
import app.utils.DateUtil;

@Controller
public class WorkManageController {
	public static Logger logger=LogManager.getLogger(WorkManageController.class);
	@Autowired
	private WorkManageService workManageService;
	@Autowired
	private CommentService commentService;
	@Autowired
	private FileService fileService;
	@Autowired
	private FixOrderService fixOrderService;
	
	@RequestMapping("workImport")
	public String showWorkImport(HttpServletRequest request){
		List<Worker> works = workManageService.findAllWork();
		request.setAttribute("works", works);
		return "admin/workImport";
	}
	
	@RequestMapping("showSingleImport")
	public String showSingleImport(HttpServletRequest request){
		return "admin/workSingleImport";
	}
	
	@RequestMapping("singleImport")

	public String singleImport(@Validated Worker work ,BindingResult result,HttpServletRequest request){
		
		System.out.println(work.toString());
		HashMap<String, String> errors = new HashMap<String, String>();
		if(result.hasErrors()){
			List<FieldError> fieldErrors = result.getFieldErrors();
			for(FieldError fieldError : fieldErrors){
				errors.put(fieldError.getField(),fieldError.getDefaultMessage());
			}
			System.out.println(errors.toString());
			request.setAttribute("errors", errors);
			return "admin/workSingleImport";
		}else{
			workManageService.singleImport(work);
			List<Worker> works = workManageService.findAllWork();
			request.setAttribute("works", works);
			return "admin/workImport";
		}

	}
	
	@RequestMapping("batchImport")
	public String batchImport(HttpServletRequest request,@RequestParam("file") MultipartFile file){
		String message ="";
		if(!file.isEmpty()){
			String path=request.getSession().getServletContext().getRealPath(Config.UPLOAD_EXCEL_PATH);
	    	String fileName=System.currentTimeMillis()+ file.getOriginalFilename();
	    	System.out.print("path:"+path);
	    	FileInfo fileInfo=new FileInfo(path,fileName);
	    	File excelFile = new File(path,fileName);
			try {
				FileUtils.copyInputStreamToFile(file.getInputStream(), excelFile);

			} catch (IOException e) {
				e.printStackTrace();			
			}
			String suffix  = fileName.substring(fileName.lastIndexOf("."));
			if(suffix.equals(".xlsx")){
				int judge = workManageService.analyzeExcel(excelFile);
				if(judge==1){
					message = "<script>alert(\"上传成功\")</script>";
				}else{
					if(excelFile.exists()){
						excelFile.delete();
					}
					message = "<script>alert(\"请按照模板填写EXCEL\")</script>";
				}
			}else{
				if(excelFile.exists()){
					excelFile.delete();
				}
				message="<script>alert(\"文件格式不正确,请选择EXCEL\")</script>";
			}
			
			int fileId=fileService.addFileInfo(fileInfo);
		}
		request.setAttribute("message", message);
		List<Worker> works = workManageService.findAllWork();
		request.setAttribute("works", works);
		return "admin/workImport";
	}
	
	@RequestMapping(value = "/findwork/{id}",method = RequestMethod.GET)
	public String findWorkById(@PathVariable("id") int id,HttpServletRequest request){
		Worker work = workManageService.findWorkById(id);
		System.out.println(work.toString());
		request.setAttribute("work", work);
		return "admin/workUpdate";
	}
	
	//lhe 
	@RequestMapping(value = "/findWorker/{id}",method = RequestMethod.GET)
	@ResponseBody
	public Result findWorker(@PathVariable("id") int id,HttpServletRequest request){
		Result result=new Result(Config.SUCCESS_CODE, "");
		try{
			Worker worker = workManageService.findWorkById(id);
			result.setRow(worker);
		}
		catch(Exception e){
			e.printStackTrace();
			result.setCode(Config.FAIL_CODE);
			return result;
		}
		return result;
	}
	
	@RequestMapping(value = "/updateWork",method = RequestMethod.POST)
	public String updateWorkById(Worker work,HttpServletRequest request){
		System.out.println(work.toString());
		workManageService.updateWorkById(work);
		
		List<Worker> works = workManageService.findAllWork();
		request.setAttribute("works", works);
		return "admin/workImport";
	}
	
	@RequestMapping(value = "/deleteWork/{id}")
	public String deleteWorkById(@PathVariable("id") Integer id,HttpServletRequest request){
		workManageService.deleteWorkById(id);
		
		List<Worker> works = workManageService.findAllWork();
		request.setAttribute("message", "<script>alert(\"删除成功\")</script>");
		request.setAttribute("works", works);
		return "admin/workImport";
	}
	
	@RequestMapping(value = "/workerList")
	@ResponseBody
	public Result list(){
		Result result=new Result();
		try{
			List<Worker> workerlist=workManageService.findAllWork();
			result.setCode(Config.SUCCESS_CODE);
			result.setRow(workerlist);
		}
		catch(Exception e){
			e.printStackTrace();
			result.setCode(Config.FAIL_CODE);
			return result;
		}
		return result;
	}
	@RequestMapping(value = "/showChart")
	public String showWorkerChart(){
		return "admin/workChart";
	}
	@RequestMapping(value = "/workerChart")
	@ResponseBody
	public ArrayList<WorkerChart> getWorkerChart(HttpServletRequest request){		
		List<Worker> works = workManageService.findAllWork();
		ArrayList<WorkerChart> workerCharts = new ArrayList<WorkerChart>();
		for(int i = 0; i < works.size(); i++){
			WorkerChart workerChart = new WorkerChart();
			Worker worker = workManageService.findWorkById(works.get(i).getId());
			List<Assess> assesses =commentService.findAssessByWorkId(works.get(i).getId());
			workerChart.setName(worker.getName());
			workerChart.setAveOrderNum(String.valueOf(assesses.size()));
			double sum = 0;
			int count = 0;
			for(int j = 0;j<assesses.size();j++){
				if(!"".equals(assesses.get(j).getRank())&&assesses.get(j).getRank()!=null){
					sum+=Double.valueOf(assesses.get(j).getRank());
					count++;
				}
			}
			if(sum == 0){
				workerChart.setAveRank("0");
			}else{
				workerChart.setAveRank(String.valueOf(sum/count));
			}			
			workerCharts.add(workerChart);
		}
		
		/*request.setAttribute("works", works);*/
		return workerCharts;
	}
	
	@RequestMapping(value = "/showDiscountedChart")
	public String showDiscountedChart(){
		return "admin/discountedChart";
	}
	
	@RequestMapping(value = "/discountedChart")
	@ResponseBody
	public ArrayList<DiscountedChart> discountedChart(){
		ArrayList<DiscountedChart> discountedCharts = new ArrayList<>();
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
		Date currentDay = new Date();	
		Date nextDay = DateUtil.getNextDay(currentDay);
		for(int i = 0;i<7;i++){
			DiscountedChart discountedChart = new DiscountedChart();
			Date before = DateUtil.getPreDay(nextDay,i+1);
			Date after = DateUtil.getPreDay(nextDay,i);
			System.out.println(sdf.format(before)+sdf.format(after));
			Integer userOrderNum = fixOrderService.findByTime(sdf.format(before),sdf.format(after));
			Integer workOrderNum = fixOrderService.findByTimeForWork(sdf.format(before),sdf.format(after));
			discountedChart.setDate(sdf.format(before));
			discountedChart.setUserOrderNum(userOrderNum);
			discountedChart.setWorkOrderNum(workOrderNum);
			discountedCharts.add(discountedChart);
		}

		
		return discountedCharts;
	}
	
}
